package com.luozm.captcha;

import ohos.agp.components.AttrSet;
import ohos.agp.components.element.Element;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayAttributes;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;

import java.math.BigDecimal;
import java.util.Optional;

/**
 * Created by luozhanming on 2018/1/17.
 */

public class Utils {


    public static DisplayAttributes getScreenPiex(Context context){
        // 获取屏幕密度
        Optional<Display> display = DisplayManager.getInstance().getDefaultDisplay(context);
        if (display.isPresent()) {
            DisplayAttributes displayAttributes = display.get().getAttributes();
            return  displayAttributes;
        }
        //displayAttributes.xDpi;
        //displayAttributes.yDpi
        return null;
    }
    /**
     * dp转px
     *
     * @param  context context
     * @param dp dp
     * @return int
     * */
    public static int dp2px(Context context, float dp){
        // 获取屏幕密度
        DisplayAttributes displayAttributes = getScreenPiex(context);
        return  (int)(dp * displayAttributes.scalDensity);
    }

    static int getAttrSetInt(AttrSet attrs, String key, int def){
        if (attrs.getAttr(key).isPresent()){
            return attrs.getAttr(key).get().getIntegerValue();
        }else {
            return def;
        }
    }
    static String getAttrSetString(AttrSet attrs,String key, String str){
        if (attrs.getAttr(key).isPresent()){
            return attrs.getAttr(key).get().getStringValue();
        }else {
            return str;
        }
    }
    static Element getAttrSetElement(AttrSet attrs, String key){
        if (attrs.getAttr(key).isPresent()){
            return attrs.getAttr(key).get().getElement();
        }else {
            return null;
        }
    }

    public static float add(float a, float b) {
        BigDecimal a1 = new BigDecimal(a);
        BigDecimal b1 = new BigDecimal(b);
        return a1.add(b1).floatValue();
    }

    public static float sub(float a, float b) {
        BigDecimal a1 = new BigDecimal(a);
        BigDecimal b1 = new BigDecimal(b);
        return a1.subtract(b1).floatValue();
    }

    public static float mul(float a, float b) {
        BigDecimal a1 = new BigDecimal(a);
        BigDecimal b1 = new BigDecimal(b);
        return a1.multiply(b1).floatValue();
    }

    public static float div(float a, float b) {
        BigDecimal a1 = new BigDecimal(a);
        BigDecimal b1 = new BigDecimal(b);
        return a1.divide(b1,2,BigDecimal.ROUND_HALF_UP).floatValue();
    }
}
